package com.example.gateway.filter;

import com.example.gateway.config.JwtConfig;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/**
 * 认证过滤器 - 验证JWT令牌
 */
public class AuthFilter extends ZuulFilter {

    @Autowired
    private JwtConfig jwtConfig;

    // 不需要认证的路径
    private static final List<String> EXCLUDE_PATHS = Arrays.asList(
            "/api/users/login",
            "/api/users/register"
    );

    @Override
    public String filterType() {
        return "pre"; // 前置过滤器
    }

    @Override
    public int filterOrder() {
        return 1; // 执行顺序
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String path = request.getRequestURI();

        // 检查是否在排除路径中
        return !EXCLUDE_PATHS.stream().anyMatch(path::startsWith);
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        // 从请求头获取Authorization字段
        String token = getJwtFromRequest(request);

        if (token == null) {
            // 未提供令牌，拒绝访问
            setUnauthorizedResponse(ctx, "缺少认证令牌");
            return null;
        }

        // 验证JWT令牌
        if (!jwtConfig.validateToken(token)) {
            // 令牌无效，拒绝访问
            setUnauthorizedResponse(ctx, "无效或过期的令牌");
            return null;
        }

        // 令牌有效，添加用户信息到请求头
        Claims claims = jwtConfig.parseToken(token);
        ctx.addZuulRequestHeader("X-User-Id", claims.getSubject());

        return null;
    }

    /**
     * 从请求头获取JWT令牌
     */
    private String getJwtFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }

    /**
     * 设置未授权响应
     */
    private void setUnauthorizedResponse(RequestContext ctx, String message) {
        ctx.setSendZuulResponse(false);
        ctx.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
        ctx.setResponseBody("{\"error\": \"" + message + "\"}");
        ctx.getResponse().setContentType("application/json;charset=UTF-8");
    }
}